{% extends 'base.html' %}

{% block title %}用户管理 - 固定资产管理系统{% endblock %}

{% block content %}
{% csrf_token %}
<div class="row">
    <div class="col-md-12">
        <nav aria-label="breadcrumb">
            <ol class="breadcrumb">
                <li class="breadcrumb-item"><a href="{% url 'assets:index' %}">首页</a></li>
                <li class="breadcrumb-item active" aria-current="page">用户管理</li>
            </ol>
        </nav>
        
        <div class="d-flex justify-content-between align-items-center mb-3">
            <h2><i class="fas fa-users me-2"></i>用户管理</h2>
            <div class="btn-group">
                <a href="{% url 'assets:user_create' %}" class="btn btn-primary">
                    <i class="fas fa-plus me-1"></i>新增用户
                </a>
                <button type="button" class="btn btn-outline-primary dropdown-toggle dropdown-toggle-split" data-bs-toggle="dropdown">
                    <span class="visually-hidden">更多操作</span>
                </button>
                <ul class="dropdown-menu">
                    <li><a class="dropdown-item" href="{% url 'assets:bulk_import_users' %}">
                        <i class="fas fa-upload me-2"></i>批量导入
                    </a></li>
                    <li><hr class="dropdown-divider"></li>
                    <li><a class="dropdown-item text-warning" href="#" onclick="batchToggleUserStatus(false)">
                        <i class="fas fa-user-slash me-2"></i>批量停用
                    </a></li>
                    <li><a class="dropdown-item text-success" href="#" onclick="batchToggleUserStatus(true)">
                        <i class="fas fa-user-check me-2"></i>批量激活
                    </a></li>
                    <li><hr class="dropdown-divider"></li>
                    <li><a class="dropdown-item text-danger" href="#" onclick="batchDeleteUsers()">
                        <i class="fas fa-trash me-2"></i>批量删除
                    </a></li>
                </ul>
            </div>
        </div>
        
        <!-- 搜索和筛选 -->
        <div class="card mb-4">
            <div class="card-body">
                <form method="get" class="row g-3">
                    <div class="col-md-6">
                        <div class="input-group">
                            <input type="text" class="form-control" name="search" placeholder="搜索用户名、姓名或邮箱..." value="{{ search_query }}">
                            <button class="btn btn-outline-secondary" type="submit">
                                <i class="fas fa-search me-1"></i>搜索
                            </button>
                        </div>
                    </div>
                    <div class="col-md-3">
                        <select class="form-select" name="status">
                            <option value="">全部状态</option>
                            <option value="active" {% if request.GET.status == 'active' %}selected{% endif %}>激活</option>
                            <option value="inactive" {% if request.GET.status == 'inactive' %}selected{% endif %}>未激活</option>
                        </select>
                    </div>
                    <div class="col-md-3">
                        <select class="form-select" name="role">
                            <option value="">全部角色</option>
                            <option value="staff" {% if request.GET.role == 'staff' %}selected{% endif %}>员工</option>
                            <option value="superuser" {% if request.GET.role == 'superuser' %}selected{% endif %}>超级用户</option>
                        </select>
                    </div>
                </form>
            </div>
        </div>

        <!-- 用户列表 -->
        <div class="card">
            <div class="card-header">
                <h5 class="mb-0">
                    <i class="fas fa-list me-2"></i>用户列表
                    {% if page_obj %}
                        <span class="badge bg-secondary ms-2">{{ page_obj.paginator.count }} 个用户</span>
                    {% endif %}
                </h5>
            </div>
            <div class="card-body">
                <form id="batchDeleteForm" method="post" action="{% url 'assets:user_batch_delete' %}">
                    {% csrf_token %}
                    <div class="table-responsive">
                        <table class="table table-striped table-hover">
                            <thead class="table-dark">
                                <tr>
                                    <th width="5%">
                                        <input type="checkbox" class="form-check-input" id="selectAllHeader" onchange="toggleSelectAll()">
                                    </th>
                                    <th width="15%">用户名</th>
                                    <th width="15%">姓名</th>
                                    <th width="20%">邮箱</th>
                                    <th width="10%">状态</th>
                                    <th width="10%">角色</th>
                                    <th width="15%">最后登录</th>
                                    <th width="10%">操作</th>
                                </tr>
                            </thead>
                            <tbody>
                                {% for user in page_obj %}
                                <tr>
                                    <td>
                                        <input type="checkbox" class="form-check-input user-checkbox" name="user_ids" value="{{ user.pk }}">
                                    </td>
                                    <td>
                                        <div class="d-flex align-items-center">
                                            <i class="fas fa-user me-2 text-muted"></i>
                                            <strong>{{ user.username }}</strong>
                                        </div>
                                    </td>
                                    <td>
                                        {% if user.first_name or user.last_name %}
                                            {{ user.first_name }} {{ user.last_name }}
                                        {% else %}
                                            <span class="text-muted">-</span>
                                        {% endif %}
                                    </td>
                                    <td>
                                        {% if user.email %}
                                            <a href="mailto:{{ user.email }}" class="text-decoration-none">
                                                <i class="fas fa-envelope me-1"></i>{{ user.email }}
                                            </a>
                                        {% else %}
                                            <span class="text-muted">-</span>
                                        {% endif %}
                                    </td>
                                    <td>
                                        {% if user.is_active %}
                                            <span class="badge bg-success">
                                                <i class="fas fa-check me-1"></i>激活
                                            </span>
                                        {% else %}
                                            <span class="badge bg-danger">
                                                <i class="fas fa-times me-1"></i>未激活
                                            </span>
                                        {% endif %}
                                    </td>
                                    <td>
                                        <div class="d-flex flex-column">
                                            {% if user.is_superuser %}
                                                <span class="badge bg-danger mb-1">
                                                    <i class="fas fa-crown me-1"></i>超级用户
                                                </span>
                                            {% endif %}
                                            {% if user.is_staff %}
                                                <span class="badge bg-info">
                                                    <i class="fas fa-user-tie me-1"></i>员工
                                                </span>
                                            {% else %}
                                                <span class="badge bg-secondary">
                                                    <i class="fas fa-user me-1"></i>普通用户
                                                </span>
                                            {% endif %}
                                        </div>
                                    </td>
                                    <td>
                                        {% if user.last_login %}
                                            <div class="text-nowrap">
                                                <i class="fas fa-clock me-1 text-muted"></i>
                                                {{ user.last_login|date:"m-d H:i" }}
                                            </div>
                                            <small class="text-muted">{{ user.last_login|date:"Y" }}</small>
                                        {% else %}
                                            <span class="text-muted">从未登录</span>
                                        {% endif %}
                                    </td>
                                    <td>
                                        <div class="btn-group btn-group-sm">
                                            <a href="{% url 'assets:user_detail' user.pk %}" class="btn btn-outline-info" title="查看详情">
                                                <i class="fas fa-eye"></i>
                                            </a>
                                            <a href="{% url 'assets:user_edit' user.pk %}" class="btn btn-outline-primary" title="编辑">
                                                <i class="fas fa-edit"></i>
                                            </a>
                                            {% if user != request.user %}
                                            <a href="{% url 'assets:user_delete' user.pk %}" class="btn btn-outline-danger" title="删除" onclick="return confirm('确定要删除用户 {{ user.username }} 吗？')">
                                                <i class="fas fa-trash"></i>
                                            </a>
                                            {% endif %}
                                        </div>
                                    </td>
                                </tr>
                                {% empty %}
                                <tr>
                                    <td colspan="8" class="text-center py-4">
                                        <div class="text-muted">
                                            <i class="fas fa-users fa-2x mb-2"></i>
                                            <p class="mb-0">暂无用户数据</p>
                                        </div>
                                    </td>
                                </tr>
                                {% endfor %}
                            </tbody>
                        </table>
                    </div>
                </form>
            </div>
        </div>

        <!-- 分页 -->
        {% if page_obj.has_other_pages %}
        <nav aria-label="页面导航" class="mt-4">
            <ul class="pagination justify-content-center">
                {% if page_obj.has_previous %}
                    <li class="page-item">
                        <a class="page-link" href="?page={{ page_obj.previous_page_number }}{% if search_query %}&search={{ search_query }}{% endif %}{% if request.GET.status %}&status={{ request.GET.status }}{% endif %}{% if request.GET.role %}&role={{ request.GET.role }}{% endif %}">
                            <i class="fas fa-chevron-left"></i>
                        </a>
                    </li>
                {% endif %}
                
                {% for num in page_obj.paginator.page_range %}
                    {% if page_obj.number == num %}
                        <li class="page-item active">
                            <span class="page-link">{{ num }}</span>
                        </li>
                    {% elif num > page_obj.number|add:'-3' and num < page_obj.number|add:'3' %}
                        <li class="page-item">
                            <a class="page-link" href="?page={{ num }}{% if search_query %}&search={{ search_query }}{% endif %}{% if request.GET.status %}&status={{ request.GET.status }}{% endif %}{% if request.GET.role %}&role={{ request.GET.role }}{% endif %}">{{ num }}</a>
                        </li>
                    {% endif %}
                {% endfor %}
                
                {% if page_obj.has_next %}
                    <li class="page-item">
                        <a class="page-link" href="?page={{ page_obj.next_page_number }}{% if search_query %}&search={{ search_query }}{% endif %}{% if request.GET.status %}&status={{ request.GET.status }}{% endif %}{% if request.GET.role %}&role={{ request.GET.role }}{% endif %}">
                            <i class="fas fa-chevron-right"></i>
                        </a>
                    </li>
                {% endif %}
            </ul>
        </nav>
        {% endif %}
    </div>
</div>

<script>
function toggleSelectAll() {
    const selectAllCheckbox = document.getElementById('selectAllHeader');
    const userCheckboxes = document.querySelectorAll('.user-checkbox');
    const isChecked = selectAllCheckbox.checked;
    
    userCheckboxes.forEach(checkbox => {
        checkbox.checked = isChecked;
    });
}

function batchDeleteUsers() {
    const checkedBoxes = document.querySelectorAll('.user-checkbox:checked');
    
    if (checkedBoxes.length === 0) {
        alert('请选择要删除的用户');
        return;
    }
    
    const usernames = Array.from(checkedBoxes).map(checkbox => {
        const row = checkbox.closest('tr');
        return row.querySelector('strong').textContent;
    });
    
    if (confirm(`确定要删除以下 ${checkedBoxes.length} 个用户吗？\n\n${usernames.join(', ')}\n\n此操作不可撤销！`)) {
        document.getElementById('batchDeleteForm').submit();
    }
}

function batchToggleUserStatus(activate) {
    const checkedBoxes = document.querySelectorAll('.user-checkbox:checked');
    
    if (checkedBoxes.length === 0) {
        alert('请选择要操作的用户');
        return;
    }
    
    // 过滤掉当前用户（不能停用自己）
    const validBoxes = Array.from(checkedBoxes).filter(checkbox => {
        return checkbox.value !== '{{ request.user.id }}';
    });
    
    if (validBoxes.length === 0) {
        alert('不能停用自己的账户');
        return;
    }
    
    const usernames = validBoxes.map(checkbox => {
        const row = checkbox.closest('tr');
        return row.querySelector('strong').textContent;
    });
    
    const action = activate ? '激活' : '停用';
    
    if (confirm(`确定要${action}以下 ${validBoxes.length} 个用户吗？\n\n${usernames.join(', ')}`)) {
        // 显示加载状态
        const loadingDiv = document.createElement('div');
        loadingDiv.className = 'alert alert-info';
        loadingDiv.innerHTML = '<i class="fas fa-spinner fa-spin me-2"></i>正在处理，请稍候...';
        document.querySelector('.col-md-12').insertBefore(loadingDiv, document.querySelector('.d-flex'));
        
        // 批量处理用户状态
        let completed = 0;
        let errors = [];
        
        validBoxes.forEach(checkbox => {
            const userId = checkbox.value;
            
            fetch(`/users/${userId}/toggle-status/`, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/x-www-form-urlencoded',
                    'X-CSRFToken': document.querySelector('[name=csrfmiddlewaretoken]').value
                },
                body: `activate=${activate}`
            })
            .then(response => response.json())
            .then(data => {
                completed++;
                
                if (!data.success) {
                    errors.push(`${usernames[validBoxes.indexOf(checkbox)]}: ${data.error}`);
                }
                
                // 所有请求完成后处理结果
                if (completed === validBoxes.length) {
                    loadingDiv.remove();
                    
                    if (errors.length === 0) {
                        showAlert('success', `成功${action} ${validBoxes.length} 个用户`);
                        setTimeout(() => window.location.reload(), 1000);
                    } else {
                        showAlert('warning', `部分操作失败：\n${errors.join('\n')}`);
                        setTimeout(() => window.location.reload(), 2000);
                    }
                }
            })
            .catch(error => {
                completed++;
                errors.push(`${usernames[validBoxes.indexOf(checkbox)]}: 网络错误`);
                
                if (completed === validBoxes.length) {
                    loadingDiv.remove();
                    showAlert('error', `操作失败：\n${errors.join('\n')}`);
                }
            });
        });
    }
}

function showAlert(type, message) {
    const alertDiv = document.createElement('div');
    alertDiv.className = `alert alert-${type === 'success' ? 'success' : type === 'warning' ? 'warning' : 'danger'} alert-dismissible fade show`;
    alertDiv.innerHTML = `
        <i class="fas fa-${type === 'success' ? 'check-circle' : type === 'warning' ? 'exclamation-triangle' : 'times-circle'} me-2"></i>
        <pre style="margin: 0; white-space: pre-wrap;">${message}</pre>
        <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
    `;
    
    document.querySelector('.col-md-12').insertBefore(alertDiv, document.querySelector('.d-flex'));
    
    setTimeout(() => {
        if (alertDiv.parentNode) {
            alertDiv.remove();
        }
    }, 5000);
}

// 监听单个复选框变化，更新全选状态
document.addEventListener('DOMContentLoaded', function() {
    const userCheckboxes = document.querySelectorAll('.user-checkbox');
    const selectAllHeader = document.getElementById('selectAllHeader');
    
    userCheckboxes.forEach(checkbox => {
        checkbox.addEventListener('change', function() {
            const checkedCount = document.querySelectorAll('.user-checkbox:checked').length;
            const totalCount = userCheckboxes.length;
            
            if (selectAllHeader) selectAllHeader.checked = checkedCount === totalCount;
        });
    });
});
</script>
{% endblock %}